<template>
  <div id="container">
    <slot></slot>
  </div>
</template>
<script>
export default {
  name: 'SelfAdaptingContainer',
  props: {},
  data() {
    return {
      desW: 1920,
      desH: 1080,
      scaleW: 1,
      scaleH: 1,
      perscaleW: 1,
      perscaleH: 1
    }
  },
  mounted() {
    this.handleResize()
    window.addEventListener('resize', this.throttle(this.handleResize, 500))
  },
  methods: {
    handleResize() {
      const app = document.getElementById('container')
      const clientW = document.body.clientWidth
      const clientH = document.body.clientHeight
      this.perscaleW = this.scaleW
      this.perscaleH = this.scaleH
      this.scaleW = clientW / this.desW
      this.scaleH = clientH / this.desH
      app.style.transformOrigin = '0 0'
      app.style.transform = `scale(${this.scaleW}, ${this.scaleH}) translate(-50%, -50%)`

      this.$emit('on-resize', this.perscaleW, this.perscaleH, this.scaleW, this.scaleH)
    },
    throttle(fn, delay) {
      let timer = null
      return function () {
        const cxt = this
        const args = arguments
        if (!timer) {
          timer = setTimeout(function () {
            fn.apply(cxt, args)
            timer = null
          }, delay)
        }
      }
    }
  }
}
</script>
<style>
#container {
  position: fixed;
  top: 50%;
  left: 50%;
  width: 1920px;
  height: 1080px;
  margin: 0;
  border: 10px solid red;
  font-size: 16px;
  background-color: #ccc;
  /* overflow: hidden; */
}
</style>
